package controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import po.LoginMessage;
import service.InsertServiceImpl;
import service.JudgeServiceImpl;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    //日志文件类
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private JudgeServiceImpl judgeServiceImpl;
    @Autowired
    private InsertServiceImpl insertServiceImpl;

    private String sessionName = "loginUser";

    //访问登陆界面
    @RequestMapping("/login")
    public String  accessLoginPage() throws Exception{
        return "login";
    }

    //访问正式初始界面
    @RequestMapping("/home")
    public String  accessHomePage() throws Exception{
        return "home";
    }


    //判断账号密码是否正确
    @RequestMapping("/validation")
    public @ResponseBody
    Map loginJudgement(@RequestBody LoginMessage loginMessage, HttpSession session){

        boolean judgeResult = false;
        judgeResult = judgeServiceImpl.loginValidation(loginMessage);

        Map<String,Object> resultMap = new HashMap();
        resultMap.put("result",judgeResult);

        //测试
        if (judgeResult){
            resultMap.put("url","../home");
            session.setAttribute(sessionName, loginMessage);
        }

        return resultMap;

    }

    //验证是否为推荐人推荐的，是，才可进行注册
    //这里就写死在程序中了
    @RequestMapping("/identify")
    public @ResponseBody
    Map identify(@RequestBody String name){
        boolean identifyResult = false;

        if(name.equals("王坚炼")  || name.equals("何思敏")){
            identifyResult = true;
        }

        Map<String,Object> resultMap = new HashMap();
        resultMap.put("result",identifyResult);

        return resultMap;
    }

    //注册账号密码
    @RequestMapping("/register")
    public @ResponseBody
    Map register(@RequestBody LoginMessage loginMessage){
        boolean registerResult = false;
        registerResult = insertServiceImpl.insertAccount(loginMessage);

        Map<String,Object> resultMap = new HashMap();
        resultMap.put("result",registerResult);

        return resultMap;
    }

    //登出账号（注销），并重定向回登陆界面
    @RequestMapping("/logout")
    public String logout(HttpSession session) throws Exception{
        session.removeAttribute(sessionName);
        session.invalidate();
        //重定向
        return "redirect:/login";
    }

}
